﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Proxys.Checkers
{
    public class PropertiesReader
    {
        protected Dictionary<String, String> mapProperties;

        public PropertiesReader(string fileName) 
        {
            mapProperties = new Dictionary<string, string>();
            string[] lines = File.ReadAllLines(fileName);
            foreach (string line in lines) 
            {
                if (string.IsNullOrEmpty(line)) { continue; }
                addToMap(line);
            }
        }
        public string[] getNames(string key ="names") 
        {
            if (!mapProperties.ContainsKey(key)) { throw new Exception("缺失names"); }
            string names =mapProperties[key];
            return names.Split(new string[]{","},StringSplitOptions.RemoveEmptyEntries);
        }

        private void addToMap(string line)
        {

            int eqIndex = line.IndexOf("=");
            if (eqIndex == 0 || eqIndex >= line.Length - 1) { throw new Exception("格式错误"); }
            string key = line.Substring(0,eqIndex).Trim();
            string value = line.Substring(eqIndex+1,line.Length-eqIndex-1).Trim();
            mapProperties[key] = value;

            //string[] strArr = line.Split('=');
            //if (strArr.Length != 2) { throw new Exception("格式错误"); }
            //mapProperties[strArr[0].Trim()] = strArr[1].Trim();
        }

        protected string getPropertyValue(string name,string defaultValue = "") 
        {
            if (mapProperties.ContainsKey(name)) 
            {
                return mapProperties[name];
            }
            return defaultValue;
        }
    }
}
